package com.zhouyu.aop;

import com.zhouyu.aop.advice.ZhouyuAfterReturningAdvice;
import com.zhouyu.aop.advice.ZhouyuAroundAdvice;
import com.zhouyu.aop.advice.ZhouyuBeforeAdvice;
import com.zhouyu.aop.advice.ZhouyuThrowsAdvice;
import com.zhouyu.aop.service.OrderInterface;
import com.zhouyu.aop.service.OrderService;
import org.aopalliance.aop.Advice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

import java.lang.reflect.Method;

/**
 * @author mimao funfind@yeah.net
 * @date ${{
 */
public class TestAop {

	public static void main(String[] args) {
		OrderService target = new OrderService();

		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(target);
//		proxyFactory.setInterfaces(OrderInterface.class);//加了这一行，就是jdk动态代理 不加使用cjlb


		proxyFactory.addAdvisor(new PointcutAdvisor() {
			//定义切点
			@Override
			public Pointcut getPointcut() {
				return new StaticMethodMatcherPointcut() {
					@Override
					public boolean matches(Method method, Class<?> targetClass) {
						//method---匹配方法
						//targetClass--匹配类型
						return method.getName().equals("a");
					}
				};
			}

			@Override
			public Advice getAdvice() {
				return new ZhouyuBeforeAdvice(); //一段代理逻辑--不能确定应用哪个方法中
			}

			@Override
			public boolean isPerInstance() {
				return false;
			}
		});

		//----------------------------------------------------------


		//两个效果一致
		proxyFactory.addAdvice(new ZhouyuAroundAdvice());

		proxyFactory.addAdvice(new MethodBeforeAdvice() {
			@Override
			public void before(Method method, Object[] args, Object target) throws Throwable {

				System.out.println("aop before");
			}
		});

		proxyFactory.addAdvice(new ZhouyuAfterReturningAdvice());

		//----------------------------------------------------------

		//组成一条链路---前面addAdvice添加的东西
		OrderService proxy = (OrderService) proxyFactory.getProxy();
		proxy.a();

	}
}
